package org.openmore.opc.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.openmore.common.CommonUtils;
import org.openmore.common.exception.OpenmoreException;
import org.openmore.opc.entity.User;
import org.openmore.opc.entity.enums.LoginType;
import org.openmore.opc.entity.enums.UserType;
import org.openmore.opc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by michaeltang on 2019/3/7.
 */
public class DefaultModularRealm extends ModularRealmAuthenticator {

    @Autowired
    @Lazy
    private UserService userService;

    private Map<String, Realm> definedRealms;
    /**
     * 判断登录类型执行操作
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Realm realm = null;
        OpenmoreToken token = (OpenmoreToken) authenticationToken;
        // 判断是否是后台用户
        if (token.getType() == LoginType.PASSWORD) {
            User user = userService.getUserByPhone(token.getTenantId(), CommonUtils.trimPhonePrefixCode(token.getUsername()));
            if (user != null && !StringUtils.isEmpty(user.getId())) {
                if(user.getUserType() == UserType.USER) {
                    // 如果是普通用户
                    realm = this.definedRealms.get("userRealm");
                } else {
                    realm = this.definedRealms.get("adminRealm");
                }
            } else {
                throw new OpenmoreException(400, "登录失败：找不到指定的用户信息。");
            }
        } else if(token.getType() == LoginType.CAPTCHA){
            User user = userService.getUserByPhone(token.getTenantId(), CommonUtils.trimPhonePrefixCode(token.getUsername()));
            if (user != null && !StringUtils.isEmpty(user.getId())) {
                if(user.getUserType() == UserType.USER) {
                    // 如果是普通用户
                    realm = this.definedRealms.get("userRealm");
                } else {
                    realm = this.definedRealms.get("adminRealm");
                }
            } else {
                //不存在用户则去自动注册
                realm = this.definedRealms.get("userRealm");
            }
        }else if (token.getType() == LoginType.WECHAT_OPEN ||
                token.getType() == LoginType.QQ ||
                token.getType() == LoginType.WEIBO||
                token.getType() == LoginType.WECHAT_MINIAPP) {
            String openId = token.getUsername();
            User user = userService.getByOpenid(token.getType(), openId);
            if (user != null && !StringUtils.isEmpty(user.getId())) {
                // 如果是普通用户
                realm = this.definedRealms.get("userRealm");
            } else {
                throw new OpenmoreException(400, "登录失败：找不到指定的用户信息。");
            }
        }
        return this.doSingleRealmAuthentication(realm, authenticationToken);
    }
    /**
     * 判断realm是否为空
     */
    @Override
    protected void assertRealmsConfigured() throws IllegalStateException {
        if (CollectionUtils.isEmpty(this.definedRealms)) {
            throw new AuthenticationException("未配置Realm!");
        }
    }

    public void setDefinedRealms(Map<String, Realm> definedRealms) {
        this.definedRealms = definedRealms;
    }
}
